/**
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.solarchallenge.client.gwtui.applicants.manageapplications;

import static com.google.solarchallenge.client.rpc.ServiceProvider.getServiceProvider;

import com.google.common.collect.ImmutableMap;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.solarchallenge.client.gwtui.mvpinterfaces.Presenter;
import com.google.solarchallenge.shared.ApplicationStatus;
import com.google.solarchallenge.shared.dtos.ApplicationDto;

import java.util.ArrayList;
import java.util.Map;

/**
 * Presenter for ManageApplications UI.
 *
 * @author Arjun Satyapal
 */
public class ManageApplicationsPresenter extends Presenter {
  ManageApplicationsDisplay display;

  private Map<Integer, ApplicationDto> map;

  public ManageApplicationsPresenter(ManageApplicationsDisplay display,
      String historyToken) {
    super(display.getSolarChallengeHeaderPanel(), historyToken);
    this.display = display;
  }

  @Override
  public void go(HasWidgets container) {
    container.clear();
    container.add(display.asWidget());
    bind();
  }

  @Override
  public void bind() {
    display.getListBoxApplicationStatus().addChangeHandler(new ChangeHandler() {
      @Override
      public void onChange(ChangeEvent event) {
        display.getListBoxApplicationDetails().clear();
        int selectedIndex = display.getListBoxApplicationStatus()
            .getSelectedIndex();

        if (selectedIndex == 0) {
          cleanState();
          return;
        }

        ApplicationStatus overallStatus = ApplicationStatus.valueOf(display
            .getListBoxApplicationStatus().getItemText(selectedIndex));
        getServiceProvider().getApplicantService().getApplicationsByStatus(
            overallStatus, new AsyncCallback<ArrayList<ApplicationDto>>() {

              @Override
              public void onSuccess(ArrayList<ApplicationDto> result) {
                int counter = 0;
                ImmutableMap.Builder<Integer, ApplicationDto> mapBuilder
                    = new ImmutableMap.Builder<Integer, ApplicationDto>();
                for (ApplicationDto currDto : result) {
                  mapBuilder.put(counter++, currDto);
                  String item = new String(currDto.getId() + " : " + currDto
                      .getApplicationDetails());
                  display.getListBoxApplicationDetails().addItem(item);
                }
                map = mapBuilder.build();
              }

              @Override
              public void onFailure(Throwable caught) {
                Window.alert("Failed to get list from the server.");
              }
            });
      }
    });

    display.getListBoxApplicationDetails().addChangeHandler(
        new ChangeHandler() {
          @Override
          public void onChange(ChangeEvent event) {
            int selectedIndex = display.getListBoxApplicationDetails()
                .getSelectedIndex();

            if (selectedIndex < 0) {
              cleanState();
              return;
            }


            ApplicationDto dto = map.get(selectedIndex);
            display.getDraftApplicationWidget().setApplicationId(dto.getId());
            display.getDraftApplicationWidget().refreshDisplay();
            display.getDraftApplicationWidget().setVisible(true);
          }
        });
  }

  private void cleanState() {
    display.getDraftApplicationWidget().setVisible(false);
    if (map != null) {
      map.clear();
    }
  }
}
